Обработчик выполнения обещания не определен в цикле обещания - PullRequest
0 голосов
/ 04 января 2019

Мне нужно выполнить обещание в цикле, а затем преобразовать результат в другое обещание.Но проблема в том, что функция Promises.all (), похоже, не принимает обещание, что код выглядит следующим образом:

return new Promise((resolve, reject) => {
    let Path = []
    let referencesLoop = []
    for (let i = 0; i < Response.length; i++) {
      referencesLoop.push(new Promise((resolve, reject) => {
        if (assetClass && searchTerm) {
          const fileName = `${process.env.FILE_OUTPUTPATH}/${assetClass}/${searchTerm.split(' ').join('_')}/${Response[i]}`
          const fileNewName = `${process.env.FILE_OUTPUTPATH}/${assetClass}/${searchTerm.split(' ').join('_')}/${searchTerm.split(' ').join('_')}_${Response[i]}`
          const bucketFileName = `${BUCKET_NAME}/${searchTerm.split(' ').join('_')}_${Response[i]}`
          if (fs.existsSync(fileName)) {
            console.log(Response[i], searchTerm)
            fs.rename(fileName, fileNewName,
              async function (error, data) {
                if (error) {
                  reject(error)
                } else {
                  try {
                    const res = await gcs.bucket(BUCKET_NAME).upload(fileNewName, {
                      // gzip: true,
                      metadata: {
                        // Enable long-lived HTTP caching headers
                        // Use only if the contents of the file will never change
                        // (If the contents will change, use cacheControl: 'no-cache')
                        cacheControl: 'public, max-age=31536000',
                      }
                    });
                    const gclouduri = `https://storage.googleapis.com/${bucketFileName}`;
                    console.log(searchTerm, 'gcloud uri')
                    console.log(gclouduri)
                    Path.push(gclouduri);
                  } catch (error) {
                    console.error(error)
                    console.log('error at bucket upload')
                    Path.push(undefined);
                  }
                }
                console.log('^^^^^^^^^^^^^^^^^^^^^^')
                console.log(Path)
                resolve(Path) //I get the Expected output here
              });
          }
        }
      }));
    }
    console.log(referencesLoop)
    Promise.all(referencesLoop).then((ref) => {
      console.log('in reference')
      resolve(ref)
    });
  })

Я попытался увидеть, что передавалось в Promise.all, и, таким образом, зарегистрировал referenceLoopи он напечатал

Promise {
    _bitField: 0,
    _fulfillmentHandler0: undefined,
    _rejectionHandler0: undefined,
    _promise0: undefined,
    _receiver0: undefined }

Кажется, что обработка обещаний где-то неверна, но я не могу выделить, где или чего именно не хватает.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...