Sails: Multiple Async/Await JS function in Sails JS Controller

Created on 20 Jun 2019  路  7Comments  路  Source: balderdashy/sails

Node version: v10.15.2
Sails version _(sails)_: 1.0.2
DB adapter & version _(e.g. [email protected])_: MongoDB shell version v3.4.3


In my controller, the fn function executes return.suucess() before my variables are properly defined. In this case, the ytb object. The sails.log of "items" is correct, but "ytb" did not return.

I also tried with Promise.then, and .all. Also, with async.each() and removing the await inside this function.

fn: async function (inputs, exits) {

        var url = require('url');
        var items = await Collection.find({});

        _.each(items, async item => {
            if (item.youtube_url) {
                var ytbUrl = item.youtube_url;
                var regexBaseUrlYtb = new RegExp('(https://www.youtube.com/channel/)');

                if (regexBaseUrlYtb.test(ytbUrl)) {
                    var ytbIdChannel = ytbUrl.replace(regexBaseUrlYtb, '');
                    var ytbChannel = await sails.helpers.youtubeApi(ytbIdChannel);
                    item.ytb = {};
                    Object.assign(item.ytb, ytbChannel);
                } 
            }
            sails.log('items: ', item)
        });
        return  exits.success({
            items
        });
    }

I expect that the ytb object will also be passed with the object item at the view, but the items object is passed without the ytb object.

Also, in general, I expect the return.success() runs only once the function finished

Thanks.

Most helpful comment

I think that the return is firing immediately because you likely need to Promise.all

```
Promise.all(
items.map(async item => {
if (item.youtube_url) {
var ytbUrl = item.youtube_url;
var regexBaseUrlYtb = new RegExp('(https://www.youtube.com/channel/)');

    if (regexBaseUrlYtb.test(ytbUrl)) {
      var ytbIdChannel = ytbUrl.replace(regexBaseUrlYtb, '');
      var ytbChannel = await sails.helpers.youtubeApi(ytbIdChannel);
      item.ytb = {};
      Object.assign(item.ytb, ytbChannel);
    } 
  }
  sails.log('items: ', item)

});
)

All 7 comments

@BenArthuys Thanks for posting! We'll take a look as soon as possible.

In the mean time, there are a few ways you can help speed things along:

  • look for a workaround. _(Even if it's just temporary, sharing your solution can save someone else a lot of time and effort.)_
  • tell us why this issue is important to you and your team. What are you trying to accomplish? _(Submissions with a little bit of human context tend to be easier to understand and faster to resolve.)_
  • make sure you've provided clear instructions on how to reproduce the bug from a clean install.
  • double-check that you've provided all of the requested version and dependency information. _(Some of this info might seem irrelevant at first, like which database adapter you're using, but we ask that you include it anyway. Oftentimes an issue is caused by a confluence of unexpected factors, and it can save everybody a ton of time to know all the details up front.)_
  • read the code of conduct.
  • if appropriate, ask your business to sponsor your issue. _(Open source is our passion, and our core maintainers volunteer many of their nights and weekends working on Sails. But you only get so many nights and weekends in life, and stuff gets done a lot faster when you can work on it during normal daylight hours.)_
  • let us know if you are using a 3rd party plugin; whether that's a database adapter, a non-standard view engine, or any other dependency maintained by someone other than our core team. _(Besides the name of the 3rd party package, it helps to include the exact version you're using. If you're unsure, check out this list of all the core packages we maintain.)_

Please remember: never post in a public forum if you believe you've found a genuine security vulnerability. Instead, disclose it responsibly.

For help with questions about Sails, click here.

Should artist.ytb = {}; read item.ytb = {};?

Should artist.ytb = {}; read item.ytb = {};?

Sorry I've edited this. just a mistake.

@BenArthuys -
I believe a semicolon is needed after sails.log('items: ', item).
It may be worthwhile to check if everything is looking defined and matching on the Collection side as well.

Interesting YouTube controller 馃憤

I think that the return is firing immediately because you likely need to Promise.all

```
Promise.all(
items.map(async item => {
if (item.youtube_url) {
var ytbUrl = item.youtube_url;
var regexBaseUrlYtb = new RegExp('(https://www.youtube.com/channel/)');

    if (regexBaseUrlYtb.test(ytbUrl)) {
      var ytbIdChannel = ytbUrl.replace(regexBaseUrlYtb, '');
      var ytbChannel = await sails.helpers.youtubeApi(ytbIdChannel);
      item.ytb = {};
      Object.assign(item.ytb, ytbChannel);
    } 
  }
  sails.log('items: ', item)

});
)

Hey, @BenArthuys! I believe that _.each takes a synchronous function, which might be why you're not getting the asynchronous behavior you expected. Does the following implementation fix the problem?

fn: async function (inputs, exits) {
        var url = require('url');
        var items = await Collection.find({});

        for(let item of items) {
            if (item.youtube_url) {
                var ytbUrl = item.youtube_url;
                var regexBaseUrlYtb = new RegExp('(https://www.youtube.com/channel/)');

                if (regexBaseUrlYtb.test(ytbUrl)) {
                    var ytbIdChannel = ytbUrl.replace(regexBaseUrlYtb, '');
                    var ytbChannel = await sails.helpers.youtubeApi(ytbIdChannel);
                    item.ytb = {};
                    Object.assign(item.ytb, ytbChannel);
                } 
            }
            sails.log('items: ', item)
        };
        return  exits.success({
            items
        });
    }

@madisonhicks Thanks so much! it fix the problem

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Noitidart picture Noitidart  路  4Comments

edy picture edy  路  4Comments

Sytten picture Sytten  路  4Comments

svmn picture svmn  路  4Comments

radoslavpetranov picture radoslavpetranov  路  4Comments