Filtering an array with a function that returns a promise

前端 未结 15 1413
遇见更好的自我
遇见更好的自我 2020-11-28 13:22

Given

let arr = [1,2,3];

function filter(num) {
  return new Promise((res, rej) => {
    setTimeout(() => {
      if( num === 3 ) {
        res(num);
         


        
15条回答
  •  余生分开走
    2020-11-28 13:56

    You can do something like this...

    theArrayYouWantToFilter = await new Promise(async (resolve) => {
      const tempArray = [];
    
      theArrayYouWantToFilter.filter(async (element, index) => {
        const someAsyncValue = await someAsyncFunction();
    
        if (someAsyncValue) {
          tempArray.push(someAsyncValue);
        }
    
        if (index === theArrayYouWantToFilter.length - 1) {
          resolve(tempArray);
        }
      });
    });
    

    Wrapped within an async function...

    
    async function filter(theArrayYouWantToFilter) {
      theArrayYouWantToFilter = await new Promise(async (resolve) => {
        const tempArray = [];
    
        theArrayYouWantToFilter.filter(async (element, index) => {
          const someAsyncValue = await someAsyncFunction();
    
          if (someAsyncValue) {
            tempArray.push(someAsyncValue);
          }
    
          if (index === theArrayYouWantToFilter.length - 1) {
            resolve(tempArray);
          }
        });
      });
    
      return theArrayYouWantToFilter;
    }
    

提交回复
热议问题