理解如何从promise链中将值返回到父函数时非常困难

问题描述 投票:0回答:1

我从这个问题的角度出发,从对这个主题的理解非常简单的角度出发,我试图找出并理解正在发生的事情。

我在How do I return the response from an asynchronous call?上阅读了这篇文章,但我无法理解。

但是,根据我的阅读,似乎标题为“如果您在代码中没有使用jQuery,这个答案适合您”这一部分是处理我正在使用的结构的部分。但是,因为示例中引用的材料与我的不同,所以我根本无法理解它,无法将其有效地应用到我的代码中。

我还阅读了很多其他关于从promise链中返回值的文章,但由于我在异步javascript和promises方面的初学者级别状态,我无法完全遵循或理解它们。

我希望有人可以用最简单的方式解释并帮助我理解如何在标题为“如果你不在代码中使用jQuery,这个答案适合你”的章节中应用这些材料,从How do I return the response from an asynchronous call?到我的代码。

我有一个函数,函数内部有一个异步的javascript。

我将我的代码更新为:

function LF(action, key, value){
  var ectcb = localforage.createInstance({name: "ectcb"});
    return ectcb.defineDriver(window.cordovaSQLiteDriver).then(function() {
    return ectcb.setDriver([
    window.cordovaSQLiteDriver._driver,
    ectcb.INDEXEDDB,
    ectcb.WEBSQL,
    ectcb.LOCALSTORAGE
    ]);
      }).then(function() {
        if (ectcb.driver().toString() = 'cordovaSQLiteDriver'){
          if (action = 'save'){ectcb.setItem(key, value); return true;} 
          else if (action = 'load'){ectcb.getItem(key, value); return true;}
          else {return false;}
          }
        else {return false;}
      }).catch(function(err) {
        return false;     
      });
    };

它最初是下面的代码

function LF(action, key, value) {
  var ectcb = localforage.createInstance({
    name: "ectcb"
  });
  var thePromiseResult = ectcb.defineDriver(window.cordovaSQLiteDriver).then(function() {
    return ectcb.setDriver([
      window.cordovaSQLiteDriver._driver,
      ectcb.INDEXEDDB,
      ectcb.WEBSQL,
      ectcb.LOCALSTORAGE
    ]);
  }).then(function() {
    if (ectcb.driver().toString() = 'cordovaSQLiteDriver') {
      if (action = 'save') {
        return ectcb.setItem(key, value);
      } else if (action = 'load') {
        return ectcb.getItem(key, value);
      } else {
        thePromiseResult = 1;
      }
    } else {
      thePromiseResult = 1;
    }
  }).catch(function(err) {});

  if (thePromiseResult = 1) {
    return false;
  } else {
    return true;
  }
};

我有一个名为thePromiseResult的变量设置为异步代码。

我试图理解如何根据代码中显示的if / else逻辑将特定值设置为thePromiseResult。

最终,有些东西会调用OF('保存','关键','价值'),我需要回到真实或错误的“某事”。

我希望有人可以解释我如何改变这些代码来实现我需要做的事情,并以一种非常简单的假人方式解释它,这样我才能真正理解正在发生的事情。

我认为在.then中设置“thePromiseResult = 1”可能不是全局设置它只是在.then中设置所需的值。

我试着看看关于这个主题的其他帖子,我无法用他们展示的各种例子来理解这些概念。

我的目标是在不同的页面上显示代码

var result = LF('fake','myKey','myValue')

if (result = false){alert("Operation Failed");
else if (result = true){alert("Operation Successful");  

我试图打破代码,以便它反映在2下完成的工作。重构代码,它讨论让你的函数接受回调。但是,因为该示例中使用的代码与我所拥有的代码完全不同,所以我只是不够了解所描述的内容。

我希望有人可以采用幼儿园编码器方法来帮助我翻译概念,以便更清楚如何将其应用于我的代码。

javascript asynchronous promise
1个回答
0
投票

如果我理解你的问题,看起来你正试图让你的承诺返回一个非承诺的结果。让我们说:

// you want "result" to be 2 here
var result = somePromise
  .then(asyncTwo => asyncTwo) // lets say the promise resolved with 2

result // still a promise, but you want it to be 2

这是对如何以及为何使用承诺的误解。处理异步代码时,回调总是在执行同步代码后解析。这意味着result永远不会被设置为你想要的2

这可能有助于推动这一点:

console.log('synchronous code start')
var result

var somePromise = new Promise((resolve) => {
  setTimeout(() => {
    resolve(2)
  }, 0)
})

somePromise.then(asyncTwo => {
  console.log('somePromise resolves with 2')
  result = asyncTwo // set result to two
})

console.log('this code is synchronous so result still equals ', result)

setTimeout(() => {
  console.log('sometime later result may equal ', result)
  console.log('but your synchronous code has already finished so this is unhelpful!') 
}, 500)

console.log('synchronous code finished')

答案是采用Promise模式,这样您就可以以逻辑方式处理异步代码。不要试图将异步结果提升到同步代码中(顺便说一下这是不可能的),而是链接额外的then / catch以将其他逻辑应用于异步结果。

// lets mock out an example of what you might get:

function asyncOneOrTwo () {
  // one or two randomly
  let oneOrTwo = Math.floor(Math.random() * 2) + 1
  return Promise.resolve(oneOrTwo)
}

function LF () {
  return asyncOneOrTwo()
    .then(oneOrTwo => {
      // you can reject with an error message instead if that's your preference
      if (oneOrTwo === 1) return Promise.reject(oneOrTwo)
      else return Promise.resolve(oneOrTwo)
    })
}

// in another file
// chain `then` or `catch` to do additional error handling
LF()
  .then(res => {
    console.log('success we got: ', res)
  })
  .catch(err => {
    console.log('fail we got: ', err)
  })
© www.soinside.com 2019 - 2024. All rights reserved.