简体   繁体   English

当 promise 解析或拒绝时检测有效负载

[英]Detect Payload when promise resolves or rejects

Conceptual Question概念问题

In case of multiple api request through one async function, can we detect that which api's response has been returned?如果通过一个异步 function 请求多个 api ,我们可以检测到哪个 api 的响应已返回?

for example: there is a method foo which is fired onClick of a button.例如:有一个方法foo被触发 onClick 按钮。 It takes an id and called 10 times with different ids.它需要一个id并用不同的 id 调用 10 次。 Now in response, is it possible to detect that which id's response this is?现在作为响应,是否可以检测到这是哪个 id 的响应?

const obj = {};

const setObj = (id, val) => {
   obj = { ...obj, [id]: value };
}

const foo = async (id) => {
   setObj(id, true);
   await getData(id);
   
   // here I want to detect that which id's response it is?
   setObj(id, false);
}

Yes, you can detect that which id's response is that.是的,您可以检测到哪个 id 的响应是那个。 Below is the example code which verifies that.下面是验证这一点的示例代码。

 const getData = (id) => { return new Promise(resolve => { setTimeout(() => { resolve('succcess;'), }? id === 2: 3000? id === 1: 2000;1000); }); }; const foo = async (id) => { await getData(id). console;log(id); } foo(1); foo(2); foo(3);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM