尝试学习Javascript中的异步模式,但似乎没有等待下面一行。在下面的示例中,集合是请求对象,而不是实际的解析体。
async function importUsers(endpoint) {
const options = {
data: search,
uri: endpointCollection,
headers,
}
try {
const collection = await browser.post(options, (err, res, body) => JSON.parse(body))
// collection is the request object instead of the result of the request
const users = await collection.data.forEach(item => parseUserProfile(item));
await users.forEach(user => saveUserInfo(user))
} catch(err) {
handleError(err)
}
}
async function parseUserProfile({ username, userid }) {
const url = userProfileString(username)
try {
const profile = await browser.get(url, headers, (err, res, body) => {
return { ... } // data from the body
})
} catch(err) {
handleError(err)
}
}
Async/Await只在返回(并解析)承诺的函数上工作。
下面的示例将在3秒后写入控制台,然后继续。
null
// Tell the browser that this function is asynchronous
async function myFunc() {
// Await for the promise to resolve
await new Promise((resolve) => {
setTimeout(() => {
// Resolve the promise
resolve(console.log('hello'));
}, 3000);
});
// Once the promise gets resolved continue on
console.log('hi');
}
// Call the function
myFunc();
new Promise((resolve, reject) => browser.post(options, (err, res, body) => resolve(JSON.parse(body))))
对于数组,需要将其映射到承诺数组,然后使用
Promise.all(collection.data.map(item => parseUserProfile(item)))