相关疑难解决方法(0)

使用`concurrent.futures.Future`作为承诺

在Python 文档中,我看到:

concurrent.futures.Future......除了测试之外,不应该直接创建.

我想在我的代码中使用它作为一个承诺,我很惊讶不建议像这样使用它.

我用例:
我有一个单独的线程,该线程读取插座来的数据包,和我有很多回调所根据包含在数据包的一些信息调用.数据包是对消费者请求的响应,所有消费者都使用单一连接.每个使用者都会收到一个promise,并为其添加一些处理程序,这些处理程序在响应到达时会被调用.

所以我不能Executor在这里使用子类,因为我只有一个线程,但我需要创建许多Futures(promises).

Promise是非常普遍的编程技术,我认为这Future是Python的承诺实现.但是如果不建议像承诺一样使用它,那么pythonistas通常用于此目的?

注意

我使用Python 2.7 反向移植的concurrent.futures2.7

python concurrency future promise concurrent.futures

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

如何知道所有Promise何时被动态"可迭代"参数解析?

我的问题是我不知道如何知道动态promise数组何时解决了所有的promise.

这是一个例子:

var promiseArray = [];
promiseArray.push(new Promise(){/*blablabla*/});
promiseArray.push(new Promise(){/*blablabla*/});
Promise.all(promiseArray).then(function(){
    // This will be executen when those 2 promises are solved.
});
promiseArray.push(new Promise(){/*blablabla*/});
Run Code Online (Sandbox Code Playgroud)

我这里有问题.当前Promise.all两个承诺被解决时,行为将被执行,但是,在这两个承诺被解决之前,第三个承诺被添加并且这个新承诺将不被考虑.

所以,我需要的是:"嘿Promise.all,你有一个动态数组来检查".我该怎么做?

请记住,这只是一个例子.我知道我可以将线Promise.all移到最后一行,但实际上新的承诺是在另一个承诺解决时动态添加的,而新的承诺也可以添加新的承诺,因此,它是一个非常动态的数组.

我拥有的真实用例是这样的:

  1. 我使用Twitter API检查是否有新的推文(使用搜索Api).
  2. 如果我发现新的推文,我将它添加到MongoDB(这里我们有Promises).
  3. 如果这些新推文与我在MongoDB中没有的用户相关(这里我们有新的承诺,因为我必须去MongoDB检查我是否有该用户),我们转到Twitter API获取用户信息(更多承诺)我们将这些新用户添加到MongoDB(是的,更多的承诺).
  4. 然后,我去MongoDB插入新的值来将新推文和那些新用户联系起来(更多的承诺!wiii!).
  5. 当所有对MongoDB的查询都已解决(所有选择,更新,插入)时,关闭MongoDB连接.

另一个难的例子:

var allPromises = [];

allPromises.push(new Promise(function(done, fail){
    mongoDB.connect(function(error){
        //Because mongoDB works with callbacks instead of promises
        if(error)
            fail();
        else
            ajax.get('/whatever').then(function(){
                if (somethingHappens) {
                    allPromises.push(new Promise(function(done, fail){ //This promise never will be take in account
                        // bla bla …
Run Code Online (Sandbox Code Playgroud)

javascript promise ecmascript-6

11
推荐指数
2
解决办法
3708
查看次数

如何拒绝(并正确使用)承诺?

短篇小说:

  • 谈到Promises/A +,拒绝承诺的正确方法是什么 - 抛出错误?但如果我错过了catch- 我的整个应用程序将会爆炸!

  • 如何使用promisify它有什么好处(也许你需要阅读更长的版本)?

  • .then(success, fail)真正的反模式,我应该使用.then(success).catch(error)

更长的版本,被描述为现实生活中的问题(希望有人阅读):

我有一个使用Bluebird(A + Promise实现库)的库,用于从数据库中获取数据(谈论Sequelize).每个查询都返回一个结果,但有时候它是空的(试图选择一些东西,但没有任何查询).承诺进入result函数,因为没有错误的原因(没有结果不是错误).例:

Entity.find(1).then(function(result) {
  // always ending here, despite result is {}
}).catch(function(error) {
  // never ends here
});
Run Code Online (Sandbox Code Playgroud)

我想包装它并检查结果是否为空(在我的代码中无法检查到这一点).我这样做了:

function findFirst() {
  return Entity.find(1).then(function(result) {
    if (result) { // add proper checks if needed
      return result; // will invoke the success function
    } else {
      // I WANT …
Run Code Online (Sandbox Code Playgroud)

javascript node.js promise bluebird

10
推荐指数
2
解决办法
8685
查看次数

使用Promises的"带超时间隔"的好模式是什么

我正在写一些代码来每N ms进行一次资源轮询,这会在M秒后超时.我希望尽可能多地使用Bluebird做出承诺.到目前为止,我提出的解决方案使用节点的间隔,可取消的蓝鸟承诺和蓝鸟的超时功能.

我想知道是否有更好的方法来实现蓝鸟和一般承诺的间隔时间?主要是通过确保间隔在该点停止并且永远不会无限期地继续.

var Promise = require('bluebird');

function poll() {
  var interval;

  return new Promise(function(resolve, reject) {
    // This interval never resolves. Actual implementation could resolve. 
    interval = setInterval(function() {
      console.log('Polling...')
    }, 1000).unref();
  })
    .cancellable()
    .catch(function(e) {
      console.log('poll error:', e.name);
      clearInterval(interval);
      // Bubble up error
      throw e;
    });
}

function pollOrTimeout() {
  return poll()
    .then(function() {
      return Promise.resolve('finished');
    })
    .timeout(5000)
    .catch(Promise.TimeoutError, function(e) {
      return Promise.resolve('timed out');
    })
    .catch(function(e) {
      console.log('Got some other error');
      throw e;
    });
}

return pollOrTimeout()
  .then(function(result) …
Run Code Online (Sandbox Code Playgroud)

node.js bluebird

10
推荐指数
1
解决办法
5189
查看次数

在承诺中使用等待

将Promise的回调定义为异步似乎存在一些固有的错误:

return new Promise(async (resolve, reject) => {
  const value = await somethingAsynchronous();
  if (value === something) {
    return resolve('It worked!');
  } else {
    return reject('Nope. Try again.');
  }
});
Run Code Online (Sandbox Code Playgroud)

这显然是一个反模式,并且可能会产生编码问题.我理解,即使awaittry/ catch块中放置语句,也很容易在此处捕获错误.

我的第一个问题是,当一个人想要转发具有不同解析/拒绝值的Promise时,最好的方法是什么?用then/catch?即

return new Promise((resolve, reject) => {
  somethingAsynchronous().then(value => {
    if (value === something) {
      return resolve('It worked!');
    } else {
      return reject('Nope. Try again.');
    }
  }); // errors would now be propagated up
});
Run Code Online (Sandbox Code Playgroud)

或者你只是按照这里的 …

javascript asynchronous promise async-await ecmascript-6

10
推荐指数
2
解决办法
9945
查看次数

承诺内部承诺

我试图用Promise编写这段代码.但我不知道如何在Promise和循环中写承诺.我试着像这样想,但insertBook函数变得异步.如何同步获取bookId?

update: function(items, quotationId) {
  return new Promise(function(resolve, reject) {
    knex.transaction(function (t) {
      Promise.bind(result).then(function() {
        return process?
      }).then(function() {
        return process?
      }).then(function() {
        var promises = items.map(function (item) {
          var people = _.pick(item, 'familyName', 'firstNumber', 'tel');
          if (item.type === 'book') {
            var book = _.pick(item, 'name', 'bookNumber', 'author');
            var bookId = insertBook(t, book);
            var values = _.merge({}, people,  {quotation: quotationId}, {book: bookId});
          } else {
            var values = _.merge({}, people,  {quotation: quotationId});
          }
          return AModel.validateFor(values);
        });
        return Promise.all(promises);
      }).then(function(items) { …
Run Code Online (Sandbox Code Playgroud)

javascript promise sails.js knex.js

9
推荐指数
1
解决办法
1万
查看次数

在异步 Jest 测试中是否需要完成?

done()在 Jest 测试中与一位同事发生争执。

他在 JavaScript 方面的经验比我多几个数量级,我是在async/await被普遍接受之后加入的,加上来自 .NET 环境,所以我已经习惯了。

我写我的测试是这样的:

it("should return 200 OK for POST method", async () => {
    await request(app).post("SOMEENDPOINT")
      .attach("file", "file")
      .expect(200);
});
Run Code Online (Sandbox Code Playgroud)

他更习惯于承诺,所以会像这样编写他的测试:

it("should return 200 OK for POST method", (done) => {
  request(app).post("SOMEENDPOINT")
    .attach("file", "file")
    .expect(200, done);
});
Run Code Online (Sandbox Code Playgroud)

他对我推送到async/ 没问题await,但坚持我必须包含done,这样我要么做他的版本修改版本:

it("should return 200 OK for POST method", async (done) => {
  await request(app).post("SOMEENDPOINT")
    .attach("file", "file")
    .expect(200, done);
});
Run Code Online (Sandbox Code Playgroud)

或者:

it("should return 200 OK …
Run Code Online (Sandbox Code Playgroud)

javascript node.js async-await supertest jestjs

9
推荐指数
1
解决办法
4037
查看次数

带有异步函数的 useState 返回 Promise {<pending>}

所以,我知道这个问题已经被问了 100 次,但在我的例子中似乎没有一个解决方案有效。

我正在使用useState钩子将状态更新为initialValues获取从getInitialValues函数返回的数据的值

const [initialValues, setInitialValues] = useState(getInitialValues());
Run Code Online (Sandbox Code Playgroud)

getInitialValues函数执行逻辑检查并返回一个对象或另一个函数retrieveDetails()

const getInitialValues = () => {
   let details;
   if(!addressDetails) {
      details = retrieveDetails();
   } else {
      details = { 
         ...,
         ...,
         ...
      };
   }
   return details;
}
Run Code Online (Sandbox Code Playgroud)

该函数retrieveDetails是一个进行 API 调用的异步函数,我等待响应并返回从响应中收到的对象。

const retrieveDetails = async () => {
   const addr = addressDetails[currentAddress];
   const { addressLookup } = addr;
   const key = process.env.API_KEY;
   const query = `?Key=${key}&Id=${addressLookup}`;
   const addrDetails = await …
Run Code Online (Sandbox Code Playgroud)

javascript promise async-await reactjs es6-promise

9
推荐指数
1
解决办法
1万
查看次数

停止AngularJS承诺链

我正在试图找出一个好方法来说"做所有这些事情,但在任何一个失败的情况下保释"

我现在拥有的:

var defer = $q.defer();

this
    .load( thingy ) // returns a promise

    .then( this.doSomethingA.bind( this ) )
    .then( this.doSomethingB.bind( this ) )
    .then( this.doSomethingC.bind( this ) )
    .then( this.doSomethingD.bind( this ) )

    .then( function(){
        defer.resolve( this );
    } );
    ;

return defer.promise;
Run Code Online (Sandbox Code Playgroud)

我最终想要的是以某种方式捕获该链上的任何错误,以便我可以将其传递给defer上面的承诺.如果语法与上面的语法类似,我并不特别在意.

或者即使有人可以告诉我如何阻止上述链条.

javascript angularjs

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

AngularJS:避免在收到响应之前调用两次相同的REST服务

我有两个指令,每个指令使用包含$ q/$ http调用的同一个工厂.

angular.module("demo").directive("itemA", ["restService", function(restService) {
    return {
        restrict: "A",
        link: function(scope, element, attrs) {
            restService.get().then(function(response) {
                // whatever
            }, function(response) {
               // whatever
            });
        }
    };
}]);


angular.module("demo").directive("itemB", ["restService", function(restService) {
    return {
        restrict: "A",
        link: function(scope, element, attrs) {
            restService.get().then(function(response) {
                // whatever
            }, function(response) {
               // whatever
            });
        }
    };
}]);

angular.module("demo").factory("restService", ["$http", "$q", function($http, $q) {
    return {
       get: function() {
           var dfd = $q.defer();
           $http.get("whatever.json", {
               cache: true
           }).success(function(response) {
              // do some stuff …
Run Code Online (Sandbox Code Playgroud)

javascript asynchronous http angularjs q

8
推荐指数
1
解决办法
4189
查看次数