<!-- begin snippet: js hide: false console: true babel: false -->
async function query(num) {
let data = await request(url, {num})
console.log(num, data)
}
[1, 2].forEach(function(item){
let _self = this
(function(item) {
setTimeout(() => {
_self.query(item)
console.log(item)
}, i)
})(item)
})
// if the server response
server.get('*', function(req, res) {
let num = req.num
res.send(num)
})
ответ асинхронного запроса://1, 2//2, 1
но ожидание ответа //1, 1//2, 2 как я могу получить желаемые результаты? Как параметр запроса согласуется с результатом возврата?
Похоже, вы хотите выполнять запросы поочередно, а не параллельно. Итак, начало каждой итерации должно дождаться разрешения предыдущей итерации перед запуском. Использование await
либо for..of
или reduce
. Вы не можете выполнять запросы последовательно с forEach
.
const requests = [1, 2];
const resolveWithArg = function(arg) {
return new Promise(res => setTimeout(() => {
console.log('resolving with ' + arg);
res(arg);
}, 1000))
}
requests.reduce(async(lastPromise, arg) => {
// the reducer function isn't actually running sequentially itself, it that they all run immediately, but await the resolve of the previous iteration on the first line
await lastPromise;
const result = await resolveWithArg(arg);
console.log('got result ' + result);
}, Promise.resolve());
let _self = this
странно.