node.js:bluebird替代async.whilst?

时间:2015-09-08 09:43:13

标签: node.js bluebird async.js

我想运行一个while循环,它依赖于每次迭代更新的条件。现在的挑战是每次迭代中的代码都是异步的。

使用async.whilst()实现此目的的一种方法。但是,我正试图寻找使用蓝鸟承诺的替代方案。有没有这样的替代方案?

2 个答案:

答案 0 :(得分:1)

我建议您使用此库:https://www.npmjs.com/package/async-bluebird 具有async的相同功能,但使用蓝鸟。

答案 1 :(得分:1)

你尝试过这个吗?的 .all() -> Promise

import json
import sys

def add_to_json(json_file, node_name, value_name, value):
    update = False
    data = {}
    try:
        with open(json_file) as f:
            data = json.load(f)
    except:
        print 'opening/loading',json_file,'failed:',sys.exc_info()[0]
        return False
    if node_name in data:
        if isinstance(data[node_name],dict):
            data[node_name][value_name] = value
            update = True
        elif isinstance(data[node_name],list):
            data[node_name].append(value)
            update = True
        else:
            print value,'not added to',node_name,'since its not a list or dict'
    else: # add node_name as dict
        data[node_name] = {value_name: value}
        update = True
    if update:
        try:
            with open(json_file, 'w') as f:
                json.dump(data, f)
            print json_file,'has been updated'
            return True
        except:
            print 'writing',json_file,'failed:',sys.exc_info()[0]
            return False


!type test2.json
{"a": [1, 3, "X", true], "n": {"y": 2, "x": 1}, "e": {}, "f": []}

add_to_json('test2.json', 'n', 'z', 1)
test2.json has been updated
Out[5]: True

!type test2.json
{"a": [1, 3, "X", true], "f": [], "e": {}, "n": {"y": 2, "x": 1, "z": 1}}

add_to_json('test2.json', 'a', None, 25)
test2.json has been updated
Out[7]: True

!type test2.json
{"a": [1, 3, "X", true, 25], "n": {"y": 2, "x": 1, "z": 1}, "e": {}, "f": []}

add_to_json('test2.json', 'e', 'new_key', 'new_value')
test2.json has been updated
Out[9]: True

!type test2.json
{"a": [1, 3, "X", true, 25], "f": [], "e": {"new_key": "new_value"}, "n": {"y": 2, "x": 1, "z": 1}}

add_to_json('test2.json', 'f', None, 37)
test2.json has been updated
Out[11]: True

!type test2.json
{"a": [1, 3, "X", true, 25], "n": {"y": 2, "x": 1, "z": 1}, "e": {"new_key": "new_value"}, "f": [37]}

add_to_json('test2.json', 'new_dict', 'zebra', 23)
test2.json has been updated
Out[13]: True

!type test2.json
{"a": [1, 3, "X", true, 25], "new_dict": {"zebra": 23}, "f": [37], "e": {"new_key": "new_value"}, "n": {"y": 2, "x": 1, "z": 1}}

add_to_json('nonexistent.json', 'new_dict', 'zebra', 47)
opening/loading nonexistent.json failed: <type 'exceptions.IOError'>
Out[15]: False