需要一些关于诺言的建议,以及如何更好地写出诺言

时间:2018-11-01 18:31:55

标签: node.js promise

所以我的代码希望是简单易懂的(仍然学习不要讨厌我),我使用了一个包来获取输入图像的调色板。而且由于我需要等待才能真正实现,所以我需要等待完成。

好吧,我的问题是我在那时使用了一个then,它感觉确实很脏,可能不是正确的方法。由于这是一个学校项目,因此我并不真正在意性能,但是如果有人可以给我一些建议,如何使它更具可用性。而且我知道我将其返回到下一个承诺,因为它不在另一个链条之内,这没有任何意义

我希望我能说对了哈哈。而且如果有一些文章,我想念如何解决这个问题也很棒!

.then(response => {
  // Make copy of the response
  const bookObject = response

  // Loop through each book
  bookObject.forEach((book, index) => {

    // Find the color pallete
    splashy.fromUrl(book.coverImage)
    .then(dominantColors => {

      // Create new key and add it to the list
      bookObject[index].dominantColors = dominantColors
    })
  })

  // Pass through to 
  return bookObject
})

3 个答案:

答案 0 :(得分:3)

首先,您无需复制响应,而只是创建对其的额外引用。您实际上并不需要它。

您正在使用循环并为数组中的每个项目执行操作,但实际上您想将它们转换为可通过您的更改解决的Promises。为此,您应该使用.map()之类的东西:

// Loop through each book
return Promise.all(response.map(book =>
  // Find the color palette
  splashy.fromUrl(book.coverImage).then(
    dominantColors => {
      // Create new key and add it to the list
      book.dominantColors = dominantColors
      return book;
    })
));

这是将您的回答转换成一系列的Promise,其中每个Promise都会在添加了dominantColors的情况下解析为该书。用Promise.all()包裹它,将它从一组Promise更改为一个Promise,该Promise解析为包含结果的数组。

答案 1 :(得分:2)

如果至少使用Node版本7.6.0,则可以使用 $.ajax({ type: 'POST', url: '/cart/add.js', data: cartData, dataType: 'json', cache: false, headers: { "cache-control": "no-cache" }, success: function(cartData){ if(product == 1){ if(cartCounter == (noItems - 1)){ // console.log('update'); updateCart(); }else{ // console.log('add to cart'); cartCounter++; cartAdd(productType,1); } }else{ // console.log('update 2') updateCart(); } }, error: function(response){ alert(response); } }); 来简化此代码。如果您能够将此代码包装在async/await函数中,则它可能看起来像这样:

async

参考文献:
async function myFunction() { const response = await functionThatReturnsResponse(); const bookObject = response const morePromises = bookObject.map((book, index) => { splashy.fromUrl(book.coverImage) .then(dominantColors => { bookObject[index].dominantColors = dominantColors; }); }); await Promise.all(morePromises); return bookObject; } https://javascript.info/async-await
async/awaithttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

答案 2 :(得分:1)

如果您在.pro中返回一个Promise,则该调用将被添加到Promise链中,从而使您可以继续在顶级链接呼叫。

const call = (arg) => new Promise((resolve, reject) => resolve(arg));
call(1)
  .then((a) => call(a))
  .then((a) => console.log(a, 'Finished!')) // 1 Finished!

但是,当您在then调用中执行多个异步操作时,用例会有些复杂。您需要使用Promise.all

将它们全部分组到一个Promise中。
const call = (arg) => new Promise((resolve, reject) => resolve(arg));
call(6)
  .then(() => {
    const args = [2,3,4];
    const promises = args.map((arg) => call(arg));  // Execute the async function and store the promise into the resulting array.
    return Promise.all(promises);  // Waits for every promise in the array to complete before continuing.
  })
  .then((results) => console.log(results.join(' '), 'Finished!')) // 2 3 4 Finished!