将文本引用替换为Promises返回的数据

时间:2015-03-26 17:41:11

标签: javascript regex node.js promise bluebird

我有一个像这样的博客文章:

var post ="## Cool Post [embed]https://soundcloud.com/wonnemusik/teaser-schotone-dear-thomson-button-remix[/embed]"
+ "Here comes another one  [embed]https://soundcloud.com/straightech-bonn-podcast/straightech-and-friends-7-oscar-ozz[/embed]";

现在每次出现[embed]soundcloud-url[/embed]我需要调用他们的API端点http://api.soundcloud.com/resolve.json?url=soundcloud-url&client_id=my-id,解析返回的JSON并用我自己的标记替换[embed]

如何使用Promises来使用它?

var post ="## Cool Post [embed]https://soundcloud.com/wonnemusik/teaser-schotone-dear-thomson-button-remix[/embed]"
+ "Here comes another one  [embed]https://soundcloud.com/straightech-bonn-podcast/straightech-and-friends-7-oscar-ozz[/embed]"
var re = /\[embed\](.*)\[\/embed\]/gm;
var m;

do {
    m = re.exec(post);
    if (m) {
      var apiCallUrl = "http://api.soundcloud.com/resolve.json?url=" + m[1] '&client_id=...'
      request(apiCallUrl).then(function(body) {
        var trackinfo = JSON.parse(body[0].body)
        return trackinfo.title
     }
    }
} while (m);

// have all promises fulfilled and old embed in post-var replaced

2 个答案:

答案 0 :(得分:1)

我没有特别使用bluebird,但通常an all method包含一组promises(或将promises作为参数)。浏览蓝鸟的API文档,他们确实可以使用all方法。你想在你的do / while循环中创建一个promises数组,然后在最后调用all

var resultPromises = [];
var m;
do {
    m = re.exec(post);
    if (m) {
        var apiCallUrl = "http://api.soundcloud.com/resolve.json?url=" + m[1] '&client_id=...'
        resultPromises.push(request(apiCallUrl));
    }
} while (m);

// have all promises fulfilled and old embed in post-var replaced
Promise.all(resultPromises).then(function (results) {
    // do stuff.
});

现在,如果要将原始文本替换为promise的结果,则还需要将匹配项存储在数组中。 results的{​​{1}}参数将是响应的数组,按照它们最初添加到数组的顺序。所以,你可以这样做:

then

答案 1 :(得分:1)

您可以使用处理异步回调的this replace function

var post = "## Cool Post [embed]https://soundcloud.com/wonnemusik/teaser-schotone-dear-thomson-button-remix[/embed]"
         + "Here comes another one  [embed]https://soundcloud.com/straightech-bonn-podcast/straightech-and-friends-7-oscar-ozz[/embed]"
var re = /\[embed\](.*)\[\/embed\]/gm;

return replaceAsync(post, re, function(m, url) {
     var apiCallUrl = "http://api.soundcloud.com/resolve.json?url=" + url + '&client_id=…'
     return request(apiCallUrl).then(function(res) {
         return JSON.parse(res[0].body).title;
     });
});