简体   繁体   English

如何使用承诺执行函数并通过 API 调用多次检查其值并使用该值执行另一个函数?

[英]How can I execute a function with promises and check its value multiple times by API call and execute another function with the value?

I'm working on an app where I need to make an API call which is in a function then use its value to make another API call.我正在开发一个应用程序,我需要在函数中进行 API 调用,然后使用其值进行另一个 API 调用。 But the first API call's value is not readily available as it depends on some external factors.但是第一个 API 调用的值并不容易获得,因为它取决于一些外部因素。 So after making the first API call I need to make 3 API calls in 5 second intervals to check if the value is available or not.因此,在进行第一次 API 调用后,我需要以 5 秒为间隔进行 3 次 API 调用,以检查该值是否可用。 If it is then make the second API call else don't make the second API call.如果是,则进行第二次 API 调用,否则不要进行第二次 API 调用。

Now I know I have to do this Promises and I tried doing it but I'm not sure if what I'm doing is right.现在我知道我必须做这个 Promises 并且我尝试这样做,但我不确定我所做的是否正确。

This is what I could do about the Promise function:这就是我可以对 Promise 函数做的事情:

const promiseFunc = ( param1, param2 ) => {

     return new Promise(( resolve, reject ) => {
           
          const func1 = api1( param1 );

          if ( func1.code === '200' ) {
      
                const startInterval = setInterval( () => {
 
                       const check = getValue();

                              if ( check && check === param2 ) {
                                    clearInterval( startInterval );
                                    resolve();
                               } else {
                                    reject();
                               }
                       
                }, 5000);

          } else {
                reject();
          }

     });

}

So what is happening in the above func is that it takes two parameters for calling the api calls.所以在上面的 func 中发生的事情是它需要两个参数来调用 api 调用。 func1 is executed and if it returns 200 then start the interval timer. func1被执行,如果它返回 200,则启动间隔计时器。 Please note that api1 function call is the API call.请注意, api1函数调用是 API 调用。 I tried using await there but it throws error.我尝试在那里使用 await 但它会引发错误。 And I'm not sure if I can use async/await inside a Promise function.而且我不确定是否可以在 Promise 函数中使用 async/await。

Moving on, check variable starts making api calls ( getValue() is also a function which includes the api endpoints) to check the value if it is available or not.继续, check变量开始进行 api 调用( getValue()也是一个包含 api 端点的函数)以检查值是否可用。 if it is then resolve, if it doesn't then reject.如果是,则解决,如果不是,则拒绝。

Here's how I'm executing the promiseFunc in sequence:这是我按顺序执行 promiseFunc 的方式:

promiseFunc( myChosenValue1, myChosenValue2 )
     .then( data => {
            return promiseFunc( valueFromFirstExecution1, valueFromFirstExecution2 )       
     })
     .then( () => {
           console.log( 'Successfully executed both the functions' );
     })
     .catch( e => {
           console.log( e );
     });

This is the farthest I could go in writing a Promise function and I know there are multiple issues in the above code.这是我在编写 Promise 函数时所能做的最远的一步,我知道上面的代码中存在多个问题。 The first function gets executed properly but then I get this error TypeError: Cannot read property 'code' of undefined .第一个函数正确执行,但随后出现此错误TypeError: Cannot read property 'code' of undefined Also, I'm not sure if the API calls in setInterval would run.另外,我不确定 setInterval 中的 API 调用是否会运行。 Any thoughts?有什么想法吗?

So you have a couple of things going on here:所以你有几件事在这里发生:

  1. You want to poll a server-side process for completion您想轮询服务器端进程以完成
  2. You want to call another function with the result of the successful completion of the server-side process.您想使用服务器端进程成功完成的结果调用另一个函数。

So lets write some helpers:所以让我们写一些助手:

// We need a way to wait for some amount of time before
// retrying a request, sleep sleeps for n milliseconds
const sleep = (n) => new Promise(res => setTimeout(res, n));

// We need a unique sentinel value so we know when we have actual
// results from an API call instead of this default value
const sentinel = {}; // or Symbol, whatever unique you prefer

// poll will take the data necessary to make a fetch
// request and repeat it every `interval` milliseconds
// up to `maxRetries` until it gets a result
const poll = async (url, fetchOpts, interval, maxRetries) => {
  let result = sentinel; // default value
  let ticker = 0; // current number of retries
  while (result === sentinel && ticker < maxRetries) {
    // make the api call
    const resp = await fetch(url, fetchOpts);
    const data = await resp.json();

    // do we have a result?
    if (isDone(data)) { // whatever criteria == completion
      result = data; // breaks the loop
    } else {
      // wait `interval` milliseconds and try again.
      ticker++;
      await sleep(interval);
    }
  }

  // Oops! We didn't get an answer back from the
  // api in time
  if (result === sentinel) {
    throw new Error('Exceeded maxRetries!');
  }

  return result;
};

So now we can actually do the thing we want:所以现在我们实际上可以做我们想做的事情:

// call this with the eventual result, *if* we
// get one
const onSuccess = (result) => {...}; // whatever

// This is doing the actual work
const doTheThing = async () => {
  await fetch(firstApiCall); // kick off the process
  try {
    // wait for completion
    const data = await poll(url, {}, 5000, 6); // ~30sec timeout

    // pass successful result onwards
    return onSuccess(data);
  } catch (err) {
    // Error bubbling is a little weird with async
    // functions, so we'll just handle it here and
    // return undefined
    console.error(err)
    return
  }
};

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

相关问题 如何从另一个脚本调用变量以执行功能 - How can I call a variable from another script to execute a function 如何使用javascript promises执行相同的功能? - How can I make the same function execute with javascript promises? 我可以使用循环在元素ID递增的情况下多次执行相同的函数调用吗? - Can I use a loop to execute the same function call multiple times on incrementing element Id's? 如何存储要在 function 中多次使用的异步 function 的值,而不必多次进行异步调用? - How can I store the value of an async function to be used multiple times in a function without having to make the async call multiple times? 如何在调用另一个 function 之前执行 function - How to execute a function before to call another function 如何在另一个函数的返回值上执行一个函数? - how do you execute a function on the returned value of another function? 多个API调用后的角度执行功能 - Angular execute function after multiple API call 如何使用promises完成另一个Javascript函数? - How to execute a Javascript function after another has completed using promises? 如何多次调用函数? - How can I call a function multiple times? 在将它们的返回数据用于另一个函数调用之前,我如何等待所有的承诺完成? - How can I wait for multiple promises to all be done before using their return data for another function call?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM