await用法示例一

27次阅读

共计 472 个字符,预计需要花费 2 分钟才能阅读完成。

How do I access the data in a promise? I use .then():

function getFirstUser() {return getUsers().then(function(users) {return users[0].name;
    });
}

Cool… so how does async/await tie in?
Well, consider the above code. getUsers() returns a promise. Any promise we have, using ES2016, we can await. That’s literally all await means: it functions in exactly the same way as calling .then() on a promise (but without requiring any callback function). So the above code becomes:

async function getFirstUser() {let users = await getUsers();
    return users[0].name;
}

正文完
 0