相关疑难解决方法(0)

如何在.then()链中访问先前的promise结果?

我已经将我的代码重组为承诺,并构建了一个由多个回调组成的精彩长扁平承诺链.then().最后我想返回一些复合值,并且需要访问多个中间承诺结果.但是,序列中间的分辨率值不在最后一个回调的范围内,我该如何访问它们?

function getExample() {
    return promiseA(…).then(function(resultA) {
        // Some processing
        return promiseB(…);
    }).then(function(resultB) {
        // More processing
        return // How do I gain access to resultA here?
    });
}
Run Code Online (Sandbox Code Playgroud)

javascript scope promise bluebird es6-promise

607
推荐指数
10
解决办法
18万
查看次数

承诺内部承诺:从子承诺中返回变量的正确方法是什么?(JS)

我有这样的功能:

function top() {

  //promise1
  ParentPromise({
    ...some code here...
  }).then(function() {


    //promise2
        ChildPromise({
          ..some code here...
        }).then(function(response) {
         var result = response.result.items;

        });

});

};
Run Code Online (Sandbox Code Playgroud)

我需要以这种方式返回结果值:

var myresult = start();
Run Code Online (Sandbox Code Playgroud)

我怎么能这样做?谢谢

javascript promise

39
推荐指数
2
解决办法
4万
查看次数

如何使用诺言避免回调地狱?

所以我有一个帖子集合

{
  id: String,
  comments: [String], # id of Comments
  links: [String], #id of Links
}
Run Code Online (Sandbox Code Playgroud)

评论:{id:String,comment:String,}

链接:{id:String,link:String,}

通过ID查找包含评论和链接的帖子:

Posts.findOne({id: id}, function(post) {
  Comments.find({id: post.id}, function(comments) {
    Links.find({id: post.id}, function(links) {
      res.json({post: post, comments: comment, links: links})
    })
  })
})
Run Code Online (Sandbox Code Playgroud)

如何使用Promise(http://mongoosejs.com/docs/promises.html)来避免回调地狱?

var query = Posts.findOne({id: id});
var promise = query.exec();

promise.then(function (post) {
  var query1 = Comments.find({id: post.id});
  var promise1 = query1.exec();
  promise1.then(function(comments) {
    var query2 = Links.find({id: post.id});
    var promise2 = query2.exec();
    promise2.then(function(links) {
      res.json({post: post, comments: …
Run Code Online (Sandbox Code Playgroud)

javascript mongoose node.js promise

11
推荐指数
1
解决办法
7486
查看次数

通过承诺链传递变量

有一个更好的方法吗?

let foo;
return functionA().then(result => {
  foo = result;
  return functionB();
}).then(bar => {
  return functionC(foo, bar);
});
Run Code Online (Sandbox Code Playgroud)

请注意,结果functionA是必需的输入functionC.使用promise范围之外的变量工作正常,但感觉有点icky.有一个干净的惯用方法来做到这一点?

请注意,我没有机会更改我正在调用的任何函数的API.

javascript ecmascript-6 bluebird

8
推荐指数
2
解决办法
9229
查看次数

如何在没有"缩进金字塔"的情况下正确表达任意Promise链?

有一些方法,如Q.reduceQ.all这有助于展平诺言的异类集合的特定情况下诺言链.但请注意,通用案例:

const F = (x) => x;
const a = F(1);
const b = F(2);
const c = F(a + b);
const d = F(a + c);
const e = F(b + c);
console.log(e); 
Run Code Online (Sandbox Code Playgroud)

也就是说,每个术语依赖于任意先前定义的术语的一系列赋值.假设这F是一个异步调用:

const F = (x) => Q.delay(1000).return(x);
Run Code Online (Sandbox Code Playgroud)

在没有生成缩进金字塔的情况下,我无法想到表达该模式:

F(100).then(a =>
  F(200).then(b =>
    F(a+b).then(c =>
      F(a+c).then(d =>
        F(b+c).then(e =>
          F(d+e).then(f =>
            console.log(f)
          )
        )
      )
    )
  )
);
Run Code Online (Sandbox Code Playgroud)

请注意,使用返回的值不起作用:

F(100).then(a => F(200))
    .then(b => F(a+b))
    .then(c => F(a+c))
    .then(d => F(b+c)) …
Run Code Online (Sandbox Code Playgroud)

javascript promise bluebird

6
推荐指数
1
解决办法
451
查看次数

承诺,如何将变量传递给.then函数

您好,这是一个帮助我了解Promise如何.then返回工作的问题. 问题是:如何将变量限定为第二个.然后链接函数?

这是一个jsbin http://jsbin.com/xacuna/edit?js,output

我可以访问全局变量,然后将范围变量传递给第一个变量,但不是之后.

  let innerReturnFunction = (res, myName) => {
    /* this works */
    console.log(`hi from inner name: ${myName}`)
    return res
  }

 let getInnerFuncVariable = () => {
   var myName = 'arturo'

   return fetch('https://httpbin.org/get')
    .then(function (res) {
      myName = 'Bob'
      return innerReturnFunction(res, myName);
    })
    .then(function (res, myName) {
      /* doesn't work, how can I access myName */
      console.log(`in first then ${res.url}, ${myName}`)
    });
 }

getInnerFuncVariable().then(function(res, myName) {
  /* how can I access myName */
  console.log(`last called …
Run Code Online (Sandbox Code Playgroud)

javascript xmlhttprequest fetch promise

6
推荐指数
1
解决办法
5586
查看次数

如何通过promise链传递变量

我需要通过promise .then链传递一个变量.我找不到办法解决问题.我对此很陌生,所以请耐心等待!

return foo.bar(baz)
         .then((firstResult) => {
           let message = firstResult;
         })
         .then(() => foo.bar(qux)
           .then((secondResult) => {
             message =+ secondResult;
             console.log(message);
           })
         )
Run Code Online (Sandbox Code Playgroud)

这样做的正确方法是什么?

javascript variables promise

4
推荐指数
1
解决办法
82
查看次数

在 Node v12.13.0 中未调用 fsPromises.writeFile 回调

无论出于何种原因,fs.promises没有调用 for 的回调,但文档没有提到只有在出现错误时才调用它,这就是我假设会发生的情况......

fsp.writeFile('test.txt', 'callback doesnt work', 'utf8', (error) => {
  console.log('callback is never called')
  if (error) console.error(error)
})
Run Code Online (Sandbox Code Playgroud)

这在 Node.js 版本 12.13.0 上发生(或没有发生,哈哈)。

有人知道这是什么交易吗?

filesystems fs node.js promise

4
推荐指数
1
解决办法
814
查看次数

Nodejs 事件被多次发出

export function postComment(req, res) {

const user = decodeToken(req);

let saveComment, saveJob, saveUser, activity, jobUser;

function pushToJob(comment) {
    saveComment = comment;
    Job.findById(req.params.id)
        .then((data) => {
            job = data;
            data.comments.push(saveComment._id)
            return data.save()
        }).catch((err) => {
            throw new Error(`The error at pushing to job is ${err}`)
        })
}

function updateCommentWithJobId(job) {
    saveComment.jobId = {
        _id: job._id,
        title: job.title
    }
    return saveComment.save()
}

function addActivityToUser(comment) {
    saveComment = comment;
    User.findById(user._id)
        .then((data) => {
            saveUser = data;
            activity = {
                activity: 'comment',
                comment: saveComment._id, …
Run Code Online (Sandbox Code Playgroud)

node.js eventemitter

2
推荐指数
1
解决办法
3365
查看次数

如何避免承诺链钻探?

我的承诺链如下所示:

PromiseA()
.then((A) => PromiseB(A))
.then((B) => PromiseC(B))
...
.then((X) => PromiseY(X))
.then((Y) => PromiseZ(Y, A))
Run Code Online (Sandbox Code Playgroud)

如何在最后一个承诺中使用参数 A 而无需钻取所有承诺,如下所示:

PromiseA()
.then((A) => Promise.all[A, PromiseB(A)])
.then(([A, B]) => Promise.all[A, PromiseC(B)])
...
.then(([A, X]) => Promise.all[A, PromiseY(X)])
.then(([A, Y]) => PromiseZ(A, Y))
Run Code Online (Sandbox Code Playgroud)

javascript promise

2
推荐指数
1
解决办法
80
查看次数