如何发送多个API请求?所以我有下面的代码
 const productID= [12, 43, 65, 87, 45, 76, 87];
    productID.map(id => {
     API.removeItem(id, (err, response) => {
       if (response.status === 'success') {
           console.log('remove a product');
        }else {
          console.log(err); 
        }
     })
})问题是,它不会等待第一个API请求完成并返回响应,并且只删除一个项。所以基本上我想让它同步,这就是为什么我使用async await来解决我的问题。
async function removeProducts() {
    const productID = [12, 43, 65, 87, 45, 76, 87];
    const result = await Promise.all(productID.map(id => {
        API.removeItem(id, (err, response) => {
            if (response.status === 'success') {
                console.log('remove a product');
            }else {
                console.log(err); 
        }
        });
    }));
}结果与第一个代码片段几乎相同,但这一次它能够删除2个产品项。我希望仅当前一个请求完成时才发出下一个请求。我该怎么做呢?
发布于 2019-04-01 21:47:37
第二次尝试的问题是Promise.all()接受一个promises数组作为参数。Promise.all()函数本身也返回一个promise,当传入的数组中的每个promise都被解析时,promise就会被解析。
array.map不返回promise,它返回一个新数组,其中包含使用所提供的函数调用的数组中每一项的结果。阅读有关地图函数here的更多信息。
相反,为返回promise的API调用创建一个包装函数。
const productID = [12, 43, 65, 87, 45, 76, 87];
let removeProductID = (id) => {
    return new Promise((resolve, reject) => {
        API.removeItem(id, (err, response) => {
            if (response.status === 'success') {
                console.log('remove a product');
                resolve(response);
            } else {
                console.log(err);
                reject(err);
            }
        })
    });
}
let removeAllProductIDs = async () => {
    for(let id of productID) {
        await removeProductID(id);
    }
}
removeAllProductIDs();发布于 2019-04-01 21:45:56
实际上是Promise.All()发出的并行请求,所以这不是您正在寻找的解决方案。
您需要的是让生成结果,然后发出另一个请求,依此类推。因此,你需要API.removeItem来返回 Promise .if它不是,然后你可以使用Promise.if包装这个函数来返回Promise。
    async function removeItem(id) {
      return new Promise((resolve, reject) => {
        API.removeItem(id, (err, response) => {
          if (response.status === 'success') {
            resolve("message or data"); // or pass id or anything
          } else {
            console.log(err);
            reject(err)
          }
        })
      })
    }现在您可以使用此函数来生成结果。
 const productID = [12, 43, 65, 87, 45, 76, 87];
    async function removeProducts() {
       for (let i = 0; i < productID.length; i++) {
            const result = await removeItem(productID[i]); // will return resolved value here
            // sequence
          }
     }发布于 2019-04-01 21:47:40
const productID = [12, 43, 65, 87, 45, 76, 87];
function process() {
    if (productID.length == 0) return;
    var id = productID.pop();
    API.removeItem(id, (err, response) => {
       if (response.status === 'success') {
           console.log('remove a product');
           process(); // process next item if success
        } else {
          console.log(err); 
        }
    });
};
process();https://stackoverflow.com/questions/55456516
复制相似问题